import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread(r'img/img.png', 0)  # 参数0说明读入灰度图像

# %config InlinBackend.figure_format="retina"
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文
# 试试去除上一行代码会有什么影响，试试改变字体
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 获取图像高度和宽度
height = img.shape[0]
width = img.shape[1]

# 创建一幅图像
result1 = np.zeros((height, width), np.uint8)

result2 = np.zeros((height, width), np.uint8)

result3 = cv2.equalizeHist(img)

# 图像灰度上移变换 DB=DA+50
for i in range(height):
    for j in range(width):
        if int(img[i, j] + 50) > 255:
            gray = 255
        else:
            gray = int(img[i, j] + 50)
        result1[i, j] = np.uint8(gray)

for i in range(height):
    for j in range(width):
        gray = int(img[i, j] * 0.8)
        result2[i, j] = np.uint8(gray)


def histogram(image):
    (row, col) = image.shape
    # 创建长度为256的list
    hist = [0] * 256
    for i in range(row):
        for j in range(col):
            hist[image[i, j]] += 1
    return hist


plt.figure()

plt.subplot(2, 4, 1)
plt.axis('off')
plt.imshow(img, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('原图像')

plt.subplot(2, 4, 5)
image_hist = histogram(img)
plt.plot(image_hist)

plt.subplot(2, 4, 2)
plt.axis('off')
plt.imshow(result1, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('偏亮图像')

plt.subplot(2, 4, 6)
image_hist1 = histogram(result1)
plt.plot(image_hist1)

plt.subplot(2, 4, 3)
plt.axis('off')
plt.imshow(result2, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('对比度低的图像')

plt.subplot(2, 4, 7)
image_hist2 = histogram(result2)
plt.plot(image_hist2)

plt.subplot(2, 4, 4)
plt.axis('off')
plt.imshow(result3, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('均衡化后的图像')

plt.subplot(2, 4, 8)
image_hist3 = histogram(result3)
plt.plot(image_hist3)

plt.show()
